package us.esme.lib

/*
 * Copyright 2008 WorldWide Conferencing, LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions
 * and limitations under the License.
 */


import net.liftweb._
import http._
import js._
import JE._
import JsCmds._
import SHtml._
import S._
import util._
import Helpers._
import sitemap._
import mapper._
import Loc._

import us.esme._
import model._

import scala.xml.{NodeSeq}

object Track {
  def loggedIn_? = User.loggedIn_?
  
  val ifIsLoggedIn = If(loggedIn_? _, "You must be logged in")

  val menuItems =
  Menu(Loc("trackMgt", List("track", "index"), 
           "Item Tracking", Snippet("track", doTrack _), ifIsLoggedIn)) :: Nil

  def doTrack(in: NodeSeq): NodeSeq = {
    val spanName = S.attr("span_id") openOr "NA"
    val formNodes: NodeSeq = findNode(<track:form/>, in).map(_.child) openOr NodeSeq.Empty
    val span = findNode(<track:span/>, in).map(_.child) openOr NodeSeq.Empty
    val list = findNode(<track:list/>, in).map(_.child) openOr NodeSeq.Empty
    val theInput = "theName"
    val user = User.currentUser.open_! // we have a guard in the Loc so we know the user's logged in

    def addTrack(what: String): JsCmd =
    what.trim match {
      case x if x.length < 3 => S.error("Too short") ; Noop
      case x => Tracking.create.regex(x).user(user).saveMe
        S.notice("Now tracking "+x)
        redisplayTracking & SetValById(theInput, "")
    }

    def redisplayTracking: JsCmd = SetHtml(spanName, displayTracking)

    def displayTracking: NodeSeq = {
      def doLoop(toBind: NodeSeq): NodeSeq =
      Tracking.findAll(By(Tracking.user, user),
                       By(Tracking.removed, false),
                       OrderBy(Tracking.id, Ascending)).
      flatMap(t => bind("track", toBind,
                        "pattern" -> t.pattern,
                        "enabled" -> ajaxCheckbox(!t.disabled,
                                                  v => {t.disabled(!v).save
                                                        redisplayTracking}),
                        "remove" ->
                        ajaxButton(?("Remove"),
                                   () => {t.removed(true).save
                                          redisplayTracking})))

      bind("track", list, "item" -> doLoop _)
    }

    bind("track", span, "list" -> ((_: NodeSeq) => displayTracking)) ++
    ajaxForm(bind("track",
                  formNodes,
                  "text" -> text("", addTrack, "id" -> theInput)))
  }
}

